<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\SearchLog;
use think\Db;

/**
 * 视频接口
 * @ApiWeigh (82)
 */
class Video extends Api
{
    protected $noNeedLogin = ['index', 'detail'];
    protected $noNeedRight = '*';

    /**
     * 获取视频合集列表
     * 
     * @ApiTitle    (视频合集列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="type", type="string", required=false, description="类型:recommend=推荐,hot=热门,featured=精品,new=最新,my=我的视频")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "合集ID",
            "title": "合集标题",
            "subtitle": "合集副标题",
            "cover_image": "封面图片",
            "video_count": "视频数量",
            "play_count": "播放次数",
            "is_recommend": "是否推荐:0=否,1=是",
            "is_hot": "是否热门:0=否,1=是",
            "is_featured": "是否精品:0=否,1=是"
          }]
        }
      })
     */
    public function index()
    {
        $type = $this->request->get('type');
        $keyword = $this->request->get('keyword', '');
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $SearchHistoryType = 'video';
        if($type == 'my'){
            $SearchHistoryType = 'myvideo';
        }
        // 记录搜索历史
        if ($keyword && $this->auth->id) {
            \app\common\library\SearchLog::record($this->auth->id, $keyword, $SearchHistoryType);
        }
        
        $where = ['status' => 1];
        
        // 我的视频搜索
        if($type == 'my'){
            if(!$this->auth->id){
                $this->error('请先登录');
            }
            // 获取用户已开通的合集ID
            $collection_ids = \app\common\model\UserVideo::where('user_id', $this->auth->id)
                //->where('expiretime', '>', time())
                ->column('collection_id');
            if(!$collection_ids){
                $this->success('', []);
            }
            $where['id'] = ['IN', $collection_ids];
        }else{
            if($type){
                switch($type){
                    case 'recommend':
                        $where['is_recommend'] = 1;
                        break;
                    case 'hot':
                        $where['is_hot'] = 1;
                        break;
                    case 'featured':
                        $where['is_featured'] = 1;
                        break;
                }
            }
        }
        
        // 添加关键词搜索
        if($keyword){
            $where[] = function($query) use ($keyword) {
                $query->where('title', 'LIKE', "%{$keyword}%")
                    ->whereOr('subtitle', 'LIKE', "%{$keyword}%");
            };
        }
        
        $total = \app\common\model\VideoCollection::where($where)->count();
        
        $list = \app\common\model\VideoCollection::where($where)
            ->field('id,title,cover_image,video_count,play_count,subtitle,status,is_recommend,is_hot,is_featured')
            ->order($type == 'new' ? 'createtime DESC, id DESC' : 'weigh DESC, id DESC')
            ->page($page, $pageSize)
            ->select();
            
        // 处理图片完整路径    
        foreach($list as &$item) {
            $item['cover_image'] = cdnurl($item['cover_image']);
            $item['video_count'] = Db::name('video')->where('collection_id', $item['id'])->count();
        }
            
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }

    /**
     * 获取视频列表
     * 
     * @ApiTitle    (视频列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="collection_id", type="integer", required=true, description="合集ID")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "collection": {
            "id": 1,
            "title": "合集标题",
            "subtitle": "合集副标题",
            "description": "合集简介"
          },
          "video_list": {
            "total": "总记录数",
            "per_page": "每页数量",
            "current_page": "当前页码",
            "last_page": "最后页码",
            "data": [{
                "id": 1,
                "title": "视频标题",
                "cover_image": "封面图片",
                "duration": "时长/秒",
                "play_count": "播放次数",
                "is_charge": "是否收费:0=免费,1=收费",
                "can_play": "是否可播放"
            }]
          }
        }
      })
    
    
     */
    public function detail()
    {
        $collection_id = $this->request->get('collection_id');
        if(!$collection_id){
            $this->error('参数错误');
        }
        
        $collection = \app\common\model\VideoCollection::where('id', $collection_id)
            ->where('status', 1)
            ->field('id,title,description,status,subtitle,is_recommend,is_hot,is_featured')
            ->find();
            
        if(!$collection){
            $this->error('合集不存在');
        }
        
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $total = \app\common\model\Video::where('collection_id', $collection_id)
            ->where('status', 1)
            ->count();
            
        $videoList = \app\common\model\Video::where('collection_id', $collection_id)
            ->where('status', 1)
            ->field('id,title,cover_image,duration,play_count,is_charge,status,description')
            ->order('weigh DESC,id DESC')
            ->page($page, $pageSize)
            ->select();
            
        // 处理图片完整路径
        foreach($videoList as &$video) {
            $video['cover_image'] = cdnurl($video['cover_image']);
        }
            
        // 判断用户是否有权限观看收费视频    
        $hasAuth = false;
        if($this->auth->id){
            $userVideo = \app\common\model\UserVideo::where([
                'user_id' => $this->auth->id,
                'collection_id' => $collection_id
            ])
            //->where('expiretime', '>', time())
            ->find();
            
            if($userVideo){
                $hasAuth = true;
            }
        }
        
        foreach($videoList as &$video){
            $video['can_play'] = (!$video['is_charge'] || $hasAuth) ? 1 : 0;
        }
        
        $this->success('', [
            'collection' => $collection,
            'video_list' => [
                'total' => $total,
                'per_page' => $pageSize,
                'current_page' => $page,
                'last_page' => ceil($total / $pageSize),
                'data' => $videoList
            ]
        ]);
    }

    /**
     * 播放视频
     * 
     * @ApiTitle    (播放视频)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="视频ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "title": "视频标题",
          "video_url": "视频地址",
          "description": "视频简介"
        }
      })
     */
    public function play()
    {
        $this->auth->check();
        
        $id = $this->request->get('id');
        if(!$id){
            $this->error('参数错误');
        }
        
        $video = \app\common\model\Video::where('id', $id)
            ->where('status', 1)
            ->find();
            
        if(!$video){
            $this->error('视频不存在');
        }
        
        // 检查收费视频权限
        if($video['is_charge']){
            $userVideo = \app\common\model\UserVideo::where([
                'user_id' => $this->auth->id,
                'collection_id' => $video['collection_id']
            ])
            //->where('expiretime', '>', time())
            ->find();
            
            if(!$userVideo){
                $this->error('请先开通观看权限');
            }
        }
        
        // 增加播放次数
        $video->setInc('play_count');
        $video->collection->setInc('play_count');
        
        $this->success('', [
            'title' => $video['title'],
            'video_url' => cdnurl($video['video_url']),
            'description' => $video['description']
        ]);
    }
}